﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;

namespace UnitDriven
{
    public class BackgroundWorker
    {
        private CoreDispatcher _dispatcher = Window.Current.Dispatcher;

        public event EventHandler<DoWorkEventArgs> DoWork = (o, e) => { };

        public event EventHandler<WorkCompletedEventArgs> RunWorkerCompleted = (o, e) => { };

        public void RunWorkerAsync()
        {
            object result = null;
            Exception error = null;
            Task.Run(() =>
            {
                try
                {
                    var args = new DoWorkEventArgs();
                    DoWork(this, args);
                    result = args.Result;
                }
                catch (Exception ex)
                {
                    error = ex;
                }
            })
            .ContinueWith(async t =>
            {
                await _dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    () => RunWorkerCompleted(this, new WorkCompletedEventArgs { Result = result, Error = error }));
            });
        }
    }

    public class DoWorkEventArgs : EventArgs
    {
        public object Result { get; set; }
    }

    public class WorkCompletedEventArgs : EventArgs
    {
        public object Result { get; set; }
        public Exception Error { get; set; }
    }
}
